// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.1

package role

import (
	"audio-server/internal/model"
	"audio-server/internal/sqlutil"
	"context"

	"audio-server/internal/svc"
	"audio-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RolePageLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRolePageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RolePageLogic {
	return &RolePageLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RolePageLogic) RolePage(req *types.RolePageReq) (resp *types.RolePageResp, err error) {
	pageNum := req.PageNum
	if pageNum <= 0 {
		pageNum = 1
	}
	pageSize := req.PageSize
	if pageSize <= 0 {
		pageSize = 10
	}
	offset := (pageNum - 1) * pageSize
	roleModel := model.NewSysRoleModel(l.svcCtx.Conn)
	roleList, err := roleModel.FindRolePage(l.ctx, offset, pageSize)
	if err != nil {
		return nil, err
	}

	var result []types.RoleRes
	for _, role := range roleList {
		roleRes := types.RoleRes{
			RoleId:      int(role.RoleId),
			Name:        role.Name,
			Description: sqlutil.NullStringToString(role.Description),
			IsAdmin:     int(role.IsAdmin),
		}
		result = append(result, roleRes)
	}

	count, err := roleModel.FindRoleCount(l.ctx)
	return &types.RolePageResp{Total: count, List: result}, nil
}
